package light.mvc.utils;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import light.mvc.pageModel.sys.EmployInfoVO;
import light.mvc.pageModel.sys.SendEmailVO;

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class SendEmailUtil {

	public Boolean sendmail(SendEmailVO sendEmailVO) throws MessagingException {
		// 创建邮件发送类 JavaMailSender
		// 用于发送基本的文本邮件信息（不能包括附件，及图片）
		JavaMailSender sender = new JavaMailSenderImpl();
				
		// 设置邮件服务主机
		((JavaMailSenderImpl) sender).setHost(PropertiesUtil.getValue("email.properties", "mailServerHost", ""));
		// 发送者邮箱的用户名
		((JavaMailSenderImpl) sender).setUsername(PropertiesUtil.getValue("email.properties", "userName", ""));
		// 发送者邮箱的密码
		((JavaMailSenderImpl) sender).setPassword(PropertiesUtil.getValue("email.properties", "password", ""));

		// 配置文件，用于实例化java.mail.session
		Properties pro = System.getProperties();

		// 登录SMTP服务器,需要获得授权，网易163邮箱新近注册的邮箱均不能授权。
		// 测试 sohu 的邮箱可以获得授权
		pro.put("mail.smtp.auth", "true");
		pro.put("mail.smtp.socketFactory.port", "25");
		pro.put("mail.smtp.socketFactory.fallback", "false");

		// 通过文件获取信息
		((JavaMailSenderImpl) sender).setJavaMailProperties(pro);

		// 创建基本邮件信息
		// 创建多元化邮件
		MimeMessage mimeMessage = ((JavaMailSenderImpl) sender).createMimeMessage();

		// 创建 mimeMessage 帮助类，用于封装信息至 mimeMessage
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GBK");

		// 发送者地址，必须填写正确的邮件格式，否者会发送失败
		helper.setFrom(PropertiesUtil.getValue("email.properties", "userName", ""));
		// 邮件主题
		helper.setSubject(sendEmailVO.getTitle());
		// 邮件内容，简单的邮件信息只能添加文本信息
		helper.setText("");
		
		String toEmail=sendEmailVO.getToEmail();
		
		String[] email;
		if(toEmail.subSequence(toEmail.length()-1, toEmail.length()).equals(",")){
			email=toEmail.split(",");
		}else{
			email = new String[] {sendEmailVO.getToEmail()};
		}
		
		String[] to = email;
		// 邮件接收者的邮箱地址
		helper.setTo(to);

		// 如果是html代码，boolean 的参数用该为true
		helper.setText(sendEmailVO.getContant(),true);
		
		try {
			sender.send(mimeMessage);
			SysLogger.forceInfo(this.getClass(), "邮件发送成功！");
			return true;
		} catch (Exception e) {
			SysLogger.debug(this.getClass(),"邮件发送异常！"+e);
			return false;
		}

		
	}
}
